package com.appkubes.mall.admin.application.goods.sku.service.impl;

import com.appkubes.common.utils.data.string.UUIDUtils;
import com.appkubes.mall.admin.application.goods.sku.dao.SpecificTypeDao;
import com.appkubes.mall.admin.application.goods.sku.entity.model.TypeModel;
import com.appkubes.mall.admin.application.goods.sku.service.SpecificAttributeService;
import com.appkubes.mall.admin.application.goods.sku.service.SpecificTypeService;
import com.appkubes.mall.core.po.MallSpecificType;
import com.appkubes.mall.core.po.MallSpecificTypeExample;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class SpecificTypeServiceImpl implements SpecificTypeService {

    public static final char UNDERLINE = '_';

    @Autowired
    SpecificTypeDao specificTypeDao;

    @Resource
    SpecificAttributeService specificAttributeService;

    @Override
    public int add(MallSpecificType specificType) {
        specificType.setSpecificTypeKey(UUIDUtils.getUUID());
        specificType.setAppKey(null);
        return specificTypeDao.insertSelective(specificType);
    }

    @Override
    public int del(String key) {
        return specificTypeDao.deleteByPrimaryKey(key);
    }

    @Override
    public List<TypeModel> getAll(String appKey, String templateKey) {
        MallSpecificTypeExample example = new MallSpecificTypeExample();
        MallSpecificTypeExample.Criteria criteria = example.createCriteria();
        criteria.andAppKeyEqualTo(appKey);
        criteria.andTemplateKeyEqualTo(templateKey);
        example.setOrderByClause("`specific_index` DESC");
        return buildTypeModels(appKey, specificTypeDao.selectByExample(example));
    }

    private List<TypeModel> buildTypeModels(String appKey, List<MallSpecificType> types) {
        List<TypeModel> models = new ArrayList<>();
        for(MallSpecificType type: types) {
            TypeModel model = new TypeModel();
            BeanUtils.copyProperties(type, model);
            model.setLev(1);
            model.setChecked(true);
            model.setKey(model.getSpecificTypeKey());
            model.setChildren(specificAttributeService.getList(appKey, model.getSpecificTypeKey()));
            models.add(model);
        }
        return models;
    }
}
